package com.ujs.leetcode.HappyNumber;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @author zhangshihao
 * @create 2023-10-15 19:59
 */
public class HappyNumber {
    public static void main(String[] args) {
        System.out.println(isHappy(2));
        System.out.println(isHappy(7));
    }

    /**
     * 快乐数，一直加下去，那么最终要么加回了原来的数，要么就是加到了1
     *
     * @param n
     * @return
     */
    public static boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        set.add(n);
        while (true) {
            // 遍历每一个数字求其和
            int sum = 0;
            String s = String.valueOf(n);
            for (int i = 0; i < s.length(); i++) {
                int num = Integer.parseInt(String.valueOf(s.charAt(i)));
                int temp = num * num;
                sum += temp;
            }
            if (sum == 1) {
                return true;
            }
            n = sum;
            if (set.contains(n)) {
                return false;
            }
            set.add(n);
        }
    }
}
